<style>
    #currentEditingAccessRule {
        background: var(--theme_background);
        color: white;
        border-radius: 1em;
        font-weight: bolder;
    }
</style>
<div class="standardContainer">
    <div class="ui basic segment">
        <h2>Access Control</h2>
        <p>Setup blacklist or whitelist based on estimated IP geographic location or IP address. <br>
            To apply access control to a proxy hosts, create a "Access Rule" below and apply it to the proxy hosts in the HTTP Proxy tab.</p>
    </div>
    <div id="currentEditingAccessRule" class="ui basic segment">
        Select an access rule to start editing
    </div>
    <div class="ui stackable grid">
        <div class="four wide column">
            <h4>Select a rule to configure</h4>
            <p>All proxy hosts uses the "default" access rule if no rule is set.</p>
            <div class="ui selection fluid dropdown" id="accessRuleSelector">
                <input type="hidden" name="targetAccessRule" value="default" onchange="handleSelectedAccessRuleChange(this.value);">
                <i class="dropdown icon"></i>
                <div class="default text"></div>
                <div class="menu" id="accessRuleList">
                  <div class="item" data-value="default"><i class="ui yellow star icon"></i> Default</div>
                </div>
            </div>
            <div class="ui message">
                <p id="accessRuleDesc"></p>
            </div>
            
            <div class="ui divider"></div>
            <div style="width: 100%;" align="center">
                <button class="ui basic circular button" onclick="openAccessRuleEditor();" title="Edit Access Rules"><i class="ui edit icon"></i> Access Rule Editor</button>
                <button class="ui basic circular icon button" onclick="reloadAccessRulesWithFeedback();"><i class="ui green refresh icon"></i></button>
            </div>
        </div>
        <div class="twelve wide column">
            <!-- Black / White list menu-->
            <div class="ui top attached tabular menu">
                <a class="accesscontrol item active" data-tab="tab_blacklist"><i class="ui red circle times icon"></i> Blacklist</a>
                <a class="accesscontrol item" data-tab="tab_whitelist"><i class="ui green check circle icon"></i> Whitelist</a>
                <a class="accesscontrol item" data-tab="tab_quickban"><i class="ui red ban icon"></i> Quick Ban</a>
            </div>

            <!-- Blacklist Conguration Menu-->
            <div class="ui bottom attached tab segment active" data-tab="tab_blacklist">
                <h2>Blacklist</h2>
                <p>Limit access from the following country or IP address<br>
                <small>Tips: If you only want a few regions to access your site, use whitelist instead.</small></p>
                <div class="ui divider"></div>
                <div class="ui toggle checkbox">
                    <input type="checkbox" id="enableBlacklist">
                    <label>Enable Blacklist</label>
                </div>
                <div class="toggleSucc" style="float: right; display:none; color: #2abd4d;" >
                    <i class="ui green checkmark icon"></i> Setting Saved
                </div>
                <h4>Country Blacklist</h4>
                    <p><i class="yellow exclamation triangle icon"></i>
                    This will block all requests from the selected country. The requester's location is estimated from their IP address and may not be 100% accurate.</p>

                <div class="ui form">
                    <div class="field">
                        <label>Select Country</label>
                        <div id="countrySelector" class="ui fluid search multiple selection dropdown">
                            <input type="hidden" name="country">
                            <i class="dropdown icon"></i>
                            <div class="default text">Select Country</div>
                            <div class="menu">
                            <div class="item" data-value="af"><i class="af flag"></i>Afghanistan</div>
                            <div class="item" data-value="ax"><i class="ax flag"></i>Aland Islands</div>
                            <div class="item" data-value="al"><i class="al flag"></i>Albania</div>
                            <div class="item" data-value="dz"><i class="dz flag"></i>Algeria</div>
                            <div class="item" data-value="as"><i class="as flag"></i>American Samoa</div>
                            <div class="item" data-value="ad"><i class="ad flag"></i>Andorra</div>
                            <div class="item" data-value="ao"><i class="ao flag"></i>Angola</div>
                            <div class="item" data-value="ai"><i class="ai flag"></i>Anguilla</div>
                            <div class="item" data-value="ag"><i class="ag flag"></i>Antigua</div>
                            <div class="item" data-value="ar"><i class="ar flag"></i>Argentina</div>
                            <div class="item" data-value="am"><i class="am flag"></i>Armenia</div>
                            <div class="item" data-value="aw"><i class="aw flag"></i>Aruba</div>
                            <div class="item" data-value="au"><i class="au flag"></i>Australia</div>
                            <div class="item" data-value="at"><i class="at flag"></i>Austria</div>
                            <div class="item" data-value="az"><i class="az flag"></i>Azerbaijan</div>
                            <div class="item" data-value="bs"><i class="bs flag"></i>Bahamas</div>
                            <div class="item" data-value="bh"><i class="bh flag"></i>Bahrain</div>
                            <div class="item" data-value="bd"><i class="bd flag"></i>Bangladesh</div>
                            <div class="item" data-value="bb"><i class="bb flag"></i>Barbados</div>
                            <div class="item" data-value="by"><i class="by flag"></i>Belarus</div>
                            <div class="item" data-value="be"><i class="be flag"></i>Belgium</div>
                            <div class="item" data-value="bz"><i class="bz flag"></i>Belize</div>
                            <div class="item" data-value="bj"><i class="bj flag"></i>Benin</div>
                            <div class="item" data-value="bm"><i class="bm flag"></i>Bermuda</div>
                            <div class="item" data-value="bt"><i class="bt flag"></i>Bhutan</div>
                            <div class="item" data-value="bo"><i class="bo flag"></i>Bolivia</div>
                            <div class="item" data-value="ba"><i class="ba flag"></i>Bosnia</div>
                            <div class="item" data-value="bw"><i class="bw flag"></i>Botswana</div>
                            <div class="item" data-value="bv"><i class="bv flag"></i>Bouvet Island</div>
                            <div class="item" data-value="br"><i class="br flag"></i>Brazil</div>
                            <div class="item" data-value="vg"><i class="vg flag"></i>British Virgin Islands</div>
                            <div class="item" data-value="bn"><i class="bn flag"></i>Brunei</div>
                            <div class="item" data-value="bg"><i class="bg flag"></i>Bulgaria</div>
                            <div class="item" data-value="bf"><i class="bf flag"></i>Burkina Faso</div>
                            <div class="item" data-value="mm"><i class="mm flag"></i>Burma</div>
                            <div class="item" data-value="bi"><i class="bi flag"></i>Burundi</div>
                            <div class="item" data-value="tc"><i class="tc flag"></i>Caicos Islands</div>
                            <div class="item" data-value="kh"><i class="kh flag"></i>Cambodia</div>
                            <div class="item" data-value="cm"><i class="cm flag"></i>Cameroon</div>
                            <div class="item" data-value="ca"><i class="ca flag"></i>Canada</div>
                            <div class="item" data-value="cv"><i class="cv flag"></i>Cape Verde</div>
                            <div class="item" data-value="ky"><i class="ky flag"></i>Cayman Islands</div>
                            <div class="item" data-value="cf"><i class="cf flag"></i>Central African Republic</div>
                            <div class="item" data-value="td"><i class="td flag"></i>Chad</div>
                            <div class="item" data-value="cl"><i class="cl flag"></i>Chile</div>
                            <div class="item" data-value="cn"><i class="cn flag"></i>China</div>
                            <div class="item" data-value="cx"><i class="cx flag"></i>Christmas Island</div>
                            <div class="item" data-value="cc"><i class="cc flag"></i>Cocos Islands</div>
                            <div class="item" data-value="co"><i class="co flag"></i>Colombia</div>
                            <div class="item" data-value="km"><i class="km flag"></i>Comoros</div>
                            <div class="item" data-value="cg"><i class="cg flag"></i>Congo Brazzaville</div>
                            <div class="item" data-value="cd"><i class="cd flag"></i>Congo</div>
                            <div class="item" data-value="ck"><i class="ck flag"></i>Cook Islands</div>
                            <div class="item" data-value="cr"><i class="cr flag"></i>Costa Rica</div>
                            <div class="item" data-value="ci"><i class="ci flag"></i>Cote Divoire</div>
                            <div class="item" data-value="hr"><i class="hr flag"></i>Croatia</div>
                            <div class="item" data-value="cu"><i class="cu flag"></i>Cuba</div>
                            <div class="item" data-value="cy"><i class="cy flag"></i>Cyprus</div>
                            <div class="item" data-value="cz"><i class="cz flag"></i>Czech Republic</div>
                            <div class="item" data-value="dk"><i class="dk flag"></i>Denmark</div>
                            <div class="item" data-value="dj"><i class="dj flag"></i>Djibouti</div>
                            <div class="item" data-value="dm"><i class="dm flag"></i>Dominica</div>
                            <div class="item" data-value="do"><i class="do flag"></i>Dominican Republic</div>
                            <div class="item" data-value="ec"><i class="ec flag"></i>Ecuador</div>
                            <div class="item" data-value="eg"><i class="eg flag"></i>Egypt</div>
                            <div class="item" data-value="sv"><i class="sv flag"></i>El Salvador</div>
                            <div class="item" data-value="gb"><i class="gb flag"></i>England</div>
                            <div class="item" data-value="gq"><i class="gq flag"></i>Equatorial Guinea</div>
                            <div class="item" data-value="er"><i class="er flag"></i>Eritrea</div>
                            <div class="item" data-value="ee"><i class="ee flag"></i>Estonia</div>
                            <div class="item" data-value="et"><i class="et flag"></i>Ethiopia</div>
                            <div class="item" data-value="eu"><i class="eu flag"></i>European Union</div>
                            <div class="item" data-value="fk"><i class="fk flag"></i>Falkland Islands</div>
                            <div class="item" data-value="fo"><i class="fo flag"></i>Faroe Islands</div>
                            <div class="item" data-value="fj"><i class="fj flag"></i>Fiji</div>
                            <div class="item" data-value="fi"><i class="fi flag"></i>Finland</div>
                            <div class="item" data-value="fr"><i class="fr flag"></i>France</div>
                            <div class="item" data-value="gf"><i class="gf flag"></i>French Guiana</div>
                            <div class="item" data-value="pf"><i class="pf flag"></i>French Polynesia</div>
                            <div class="item" data-value="tf"><i class="tf flag"></i>French Territories</div>
                            <div class="item" data-value="ga"><i class="ga flag"></i>Gabon</div>
                            <div class="item" data-value="gm"><i class="gm flag"></i>Gambia</div>
                            <div class="item" data-value="ge"><i class="ge flag"></i>Georgia</div>
                            <div class="item" data-value="de"><i class="de flag"></i>Germany</div>
                            <div class="item" data-value="gh"><i class="gh flag"></i>Ghana</div>
                            <div class="item" data-value="gi"><i class="gi flag"></i>Gibraltar</div>
                            <div class="item" data-value="gr"><i class="gr flag"></i>Greece</div>
                            <div class="item" data-value="gl"><i class="gl flag"></i>Greenland</div>
                            <div class="item" data-value="gd"><i class="gd flag"></i>Grenada</div>
                            <div class="item" data-value="gp"><i class="gp flag"></i>Guadeloupe</div>
                            <div class="item" data-value="gu"><i class="gu flag"></i>Guam</div>
                            <div class="item" data-value="gt"><i class="gt flag"></i>Guatemala</div>
                            <div class="item" data-value="gw"><i class="gw flag"></i>Guinea-Bissau</div>
                            <div class="item" data-value="gn"><i class="gn flag"></i>Guinea</div>
                            <div class="item" data-value="gy"><i class="gy flag"></i>Guyana</div>
                            <div class="item" data-value="ht"><i class="ht flag"></i>Haiti</div>
                            <div class="item" data-value="hm"><i class="hm flag"></i>Heard Island</div>
                            <div class="item" data-value="hn"><i class="hn flag"></i>Honduras</div>
                            <div class="item" data-value="hk"><i class="hk flag"></i>Hong Kong</div>
                            <div class="item" data-value="hu"><i class="hu flag"></i>Hungary</div>
                            <div class="item" data-value="is"><i class="is flag"></i>Iceland</div>
                            <div class="item" data-value="in"><i class="in flag"></i>India</div>
                            <div class="item" data-value="io"><i class="io flag"></i>Indian Ocean Territory</div>
                            <div class="item" data-value="id"><i class="id flag"></i>Indonesia</div>
                            <div class="item" data-value="ir"><i class="ir flag"></i>Iran</div>
                            <div class="item" data-value="iq"><i class="iq flag"></i>Iraq</div>
                            <div class="item" data-value="ie"><i class="ie flag"></i>Ireland</div>
                            <div class="item" data-value="il"><i class="il flag"></i>Israel</div>
                            <div class="item" data-value="it"><i class="it flag"></i>Italy</div>
                            <div class="item" data-value="jm"><i class="jm flag"></i>Jamaica</div>
                            <div class="item" data-value="jp"><i class="jp flag"></i>Japan</div>
                            <div class="item" data-value="jo"><i class="jo flag"></i>Jordan</div>
                            <div class="item" data-value="kz"><i class="kz flag"></i>Kazakhstan</div>
                            <div class="item" data-value="ke"><i class="ke flag"></i>Kenya</div>
                            <div class="item" data-value="ki"><i class="ki flag"></i>Kiribati</div>
                            <div class="item" data-value="kw"><i class="kw flag"></i>Kuwait</div>
                            <div class="item" data-value="kg"><i class="kg flag"></i>Kyrgyzstan</div>
                            <div class="item" data-value="la"><i class="la flag"></i>Laos</div>
                            <div class="item" data-value="lv"><i class="lv flag"></i>Latvia</div>
                            <div class="item" data-value="lb"><i class="lb flag"></i>Lebanon</div>
                            <div class="item" data-value="ls"><i class="ls flag"></i>Lesotho</div>
                            <div class="item" data-value="lr"><i class="lr flag"></i>Liberia</div>
                            <div class="item" data-value="ly"><i class="ly flag"></i>Libya</div>
                            <div class="item" data-value="li"><i class="li flag"></i>Liechtenstein</div>
                            <div class="item" data-value="lt"><i class="lt flag"></i>Lithuania</div>
                            <div class="item" data-value="lu"><i class="lu flag"></i>Luxembourg</div>
                            <div class="item" data-value="mo"><i class="mo flag"></i>Macau</div>
                            <div class="item" data-value="mk"><i class="mk flag"></i>North Macedonia</div>
                            <div class="item" data-value="mg"><i class="mg flag"></i>Madagascar</div>
                            <div class="item" data-value="mw"><i class="mw flag"></i>Malawi</div>
                            <div class="item" data-value="my"><i class="my flag"></i>Malaysia</div>
                            <div class="item" data-value="mv"><i class="mv flag"></i>Maldives</div>
                            <div class="item" data-value="ml"><i class="ml flag"></i>Mali</div>
                            <div class="item" data-value="mt"><i class="mt flag"></i>Malta</div>
                            <div class="item" data-value="mh"><i class="mh flag"></i>Marshall Islands</div>
                            <div class="item" data-value="mq"><i class="mq flag"></i>Martinique</div>
                            <div class="item" data-value="mr"><i class="mr flag"></i>Mauritania</div>
                            <div class="item" data-value="mu"><i class="mu flag"></i>Mauritius</div>
                            <div class="item" data-value="yt"><i class="yt flag"></i>Mayotte</div>
                            <div class="item" data-value="mx"><i class="mx flag"></i>Mexico</div>
                            <div class="item" data-value="fm"><i class="fm flag"></i>Micronesia</div>
                            <div class="item" data-value="md"><i class="md flag"></i>Moldova</div>
                            <div class="item" data-value="mc"><i class="mc flag"></i>Monaco</div>
                            <div class="item" data-value="mn"><i class="mn flag"></i>Mongolia</div>
                            <div class="item" data-value="me"><i class="me flag"></i>Montenegro</div>
                            <div class="item" data-value="ms"><i class="ms flag"></i>Montserrat</div>
                            <div class="item" data-value="ma"><i class="ma flag"></i>Morocco</div>
                            <div class="item" data-value="mz"><i class="mz flag"></i>Mozambique</div>
                            <div class="item" data-value="na"><i class="na flag"></i>Namibia</div>
                            <div class="item" data-value="nr"><i class="nr flag"></i>Nauru</div>
                            <div class="item" data-value="np"><i class="np flag"></i>Nepal</div>
                            <div class="item" data-value="an"><i class="an flag"></i>Netherlands Antilles</div>
                            <div class="item" data-value="nl"><i class="nl flag"></i>Netherlands</div>
                            <div class="item" data-value="nc"><i class="nc flag"></i>New Caledonia</div>
                            <div class="item" data-value="pg"><i class="pg flag"></i>New Guinea</div>
                            <div class="item" data-value="nz"><i class="nz flag"></i>New Zealand</div>
                            <div class="item" data-value="ni"><i class="ni flag"></i>Nicaragua</div>
                            <div class="item" data-value="ne"><i class="ne flag"></i>Niger</div>
                            <div class="item" data-value="ng"><i class="ng flag"></i>Nigeria</div>
                            <div class="item" data-value="nu"><i class="nu flag"></i>Niue</div>
                            <div class="item" data-value="nf"><i class="nf flag"></i>Norfolk Island</div>
                            <div class="item" data-value="kp"><i class="kp flag"></i>North Korea</div>
                            <div class="item" data-value="mp"><i class="mp flag"></i>Northern Mariana Islands</div>
                            <div class="item" data-value="no"><i class="no flag"></i>Norway</div>
                            <div class="item" data-value="om"><i class="om flag"></i>Oman</div>
                            <div class="item" data-value="pk"><i class="pk flag"></i>Pakistan</div>
                            <div class="item" data-value="pw"><i class="pw flag"></i>Palau</div>
                            <div class="item" data-value="ps"><i class="ps flag"></i>Palestine</div>
                            <div class="item" data-value="pa"><i class="pa flag"></i>Panama</div>
                            <div class="item" data-value="py"><i class="py flag"></i>Paraguay</div>
                            <div class="item" data-value="pe"><i class="pe flag"></i>Peru</div>
                            <div class="item" data-value="ph"><i class="ph flag"></i>Philippines</div>
                            <div class="item" data-value="pn"><i class="pn flag"></i>Pitcairn Islands</div>
                            <div class="item" data-value="pl"><i class="pl flag"></i>Poland</div>
                            <div class="item" data-value="pt"><i class="pt flag"></i>Portugal</div>
                            <div class="item" data-value="pr"><i class="pr flag"></i>Puerto Rico</div>
                            <div class="item" data-value="qa"><i class="qa flag"></i>Qatar</div>
                            <div class="item" data-value="re"><i class="re flag"></i>Reunion</div>
                            <div class="item" data-value="ro"><i class="ro flag"></i>Romania</div>
                            <div class="item" data-value="ru"><i class="ru flag"></i>Russia</div>
                            <div class="item" data-value="rw"><i class="rw flag"></i>Rwanda</div>
                            <div class="item" data-value="sh"><i class="sh flag"></i>Saint Helena</div>
                            <div class="item" data-value="kn"><i class="kn flag"></i>Saint Kitts and Nevis</div>
                            <div class="item" data-value="lc"><i class="lc flag"></i>Saint Lucia</div>
                            <div class="item" data-value="pm"><i class="pm flag"></i>Saint Pierre</div>
                            <div class="item" data-value="vc"><i class="vc flag"></i>Saint Vincent</div>
                            <div class="item" data-value="ws"><i class="ws flag"></i>Samoa</div>
                            <div class="item" data-value="sm"><i class="sm flag"></i>San Marino</div>
                            <div class="item" data-value="gs"><i class="gs flag"></i>Sandwich Islands</div>
                            <div class="item" data-value="st"><i class="st flag"></i>Sao Tome</div>
                            <div class="item" data-value="sa"><i class="sa flag"></i>Saudi Arabia</div>
                            <div class="item" data-value="sn"><i class="sn flag"></i>Senegal</div>
                            <div class="item" data-value="cs"><i class="cs flag"></i>Serbia</div>
                            <div class="item" data-value="rs"><i class="rs flag"></i>Serbia</div>
                            <div class="item" data-value="sc"><i class="sc flag"></i>Seychelles</div>
                            <div class="item" data-value="sl"><i class="sl flag"></i>Sierra Leone</div>
                            <div class="item" data-value="sg"><i class="sg flag"></i>Singapore</div>
                            <div class="item" data-value="sk"><i class="sk flag"></i>Slovakia</div>
                            <div class="item" data-value="si"><i class="si flag"></i>Slovenia</div>
                            <div class="item" data-value="sb"><i class="sb flag"></i>Solomon Islands</div>
                            <div class="item" data-value="so"><i class="so flag"></i>Somalia</div>
                            <div class="item" data-value="za"><i class="za flag"></i>South Africa</div>
                            <div class="item" data-value="kr"><i class="kr flag"></i>South Korea</div>
                            <div class="item" data-value="es"><i class="es flag"></i>Spain</div>
                            <div class="item" data-value="lk"><i class="lk flag"></i>Sri Lanka</div>
                            <div class="item" data-value="sd"><i class="sd flag"></i>Sudan</div>
                            <div class="item" data-value="sr"><i class="sr flag"></i>Suriname</div>
                            <div class="item" data-value="sj"><i class="sj flag"></i>Svalbard</div>
                            <div class="item" data-value="sz"><i class="sz flag"></i>Swaziland</div>
                            <div class="item" data-value="se"><i class="se flag"></i>Sweden</div>
                            <div class="item" data-value="ch"><i class="ch flag"></i>Switzerland</div>
                            <div class="item" data-value="sy"><i class="sy flag"></i>Syria</div>
                            <div class="item" data-value="tw"><i class="tw flag"></i>Taiwan</div>
                            <div class="item" data-value="tj"><i class="tj flag"></i>Tajikistan</div>
                            <div class="item" data-value="tz"><i class="tz flag"></i>Tanzania</div>
                            <div class="item" data-value="th"><i class="th flag"></i>Thailand</div>
                            <div class="item" data-value="tl"><i class="tl flag"></i>Timorleste</div>
                            <div class="item" data-value="tg"><i class="tg flag"></i>Togo</div>
                            <div class="item" data-value="tk"><i class="tk flag"></i>Tokelau</div>
                            <div class="item" data-value="to"><i class="to flag"></i>Tonga</div>
                            <div class="item" data-value="tt"><i class="tt flag"></i>Trinidad</div>
                            <div class="item" data-value="tn"><i class="tn flag"></i>Tunisia</div>
                            <div class="item" data-value="tr"><i class="tr flag"></i>Turkey</div>
                            <div class="item" data-value="tm"><i class="tm flag"></i>Turkmenistan</div>
                            <div class="item" data-value="tv"><i class="tv flag"></i>Tuvalu</div>
                            <div class="item" data-value="ug"><i class="ug flag"></i>Uganda</div>
                            <div class="item" data-value="ua"><i class="ua flag"></i>Ukraine</div>
                            <div class="item" data-value="ae"><i class="ae flag"></i>United Arab Emirates</div>
                            <div class="item" data-value="us"><i class="us flag"></i>United States</div>
                            <div class="item" data-value="uy"><i class="uy flag"></i>Uruguay</div>
                            <div class="item" data-value="um"><i class="um flag"></i>Us Minor Islands</div>
                            <div class="item" data-value="vi"><i class="vi flag"></i>Us Virgin Islands</div>
                            <div class="item" data-value="uz"><i class="uz flag"></i>Uzbekistan</div>
                            <div class="item" data-value="vu"><i class="vu flag"></i>Vanuatu</div>
                            <div class="item" data-value="va"><i class="va flag"></i>Vatican City</div>
                            <div class="item" data-value="ve"><i class="ve flag"></i>Venezuela</div>
                            <div class="item" data-value="vn"><i class="vn flag"></i>Vietnam</div>
                            <div class="item" data-value="wf"><i class="wf flag"></i>Wallis and Futuna</div>
                            <div class="item" data-value="eh"><i class="eh flag"></i>Western Sahara</div>
                            <div class="item" data-value="ye"><i class="ye flag"></i>Yemen</div>
                            <div class="item" data-value="zm"><i class="zm flag"></i>Zambia</div>
                            <div class="item" data-value="zw"><i class="zw flag"></i>Zimbabwe</div>
                        </div>
                        </div>
                    </div>
                    <button class="ui basic red button" id="ban-btn" onclick="addCountryToBlacklist();"><i class="ui red ban icon"></i> Blacklist Country</button>
                </div>
                <table class="ui unstackable basic celled table">
                    <thead>
                        <tr>
                            <th>ISO Code</th>
                            <th>Remove</th>
                        </tr>
                    </thead>
                    <tbody id="banned-list">

                    </tbody>
                </table>

                <h4>IP Blacklist</h4>
                <p>Black a certain IP or IP range</p>
                <div class="ui form">
                    <div class="field">
                    <label>IP Address</label>
                    <input id="ipAddressInput" type="text" placeholder="IP Address">
                    </div>
                    <button id="addIpButton" onclick="addIpBlacklist();" class="ui basic red icon button">
                    <i class="ban icon"></i> Blacklist IP
                    </button>
                </div>
                <div class="ui message">
                    <i class="ui info circle icon"></i> IP Address support the following formats
                    <div class="ui bulleted list">
                        <div class="item">Fixed IP Address (e.g. 192.128.4.100 or fe80::210:5aff:feaa:20a2)</div>
                        <div class="item">IP Wildcard (e.g. 172.164.*.*)</div>
                        <div class="item">CIDR String (e.g. 128.32.0.1/16)</div>
                    </div>
                </div>
                <table class="ui unstackable basic celled table">
                    <thead>
                    <tr>
                        <th>IP Address</th>
                        <th>Remove</th>
                    </tr>
                    </thead>
                    <tbody id="blacklistIpTable">

                    </tbody>
                </table>
            </div>

            <!-- Whitelist Config Menu-->
            <div class="ui bottom attached tab segment" data-tab="tab_whitelist">
                <h2>Whitelist</h2>
                <p>Enable access from the following countries or IP. <br>
                    Whitelist has lower priority than blacklist if both whitelist and blacklist are enabled <br>
                    <small>Tips: You can use blacklist to fine tune whitelist coverage</small></p>
                <div class="ui divider"></div>
                <div class="ui toggle checkbox">
                    <input type="checkbox" id="enableWhitelist">
                    <label>Enable Whitelist</label>
                </div>
                <div class="toggleSucc" style="float: right; display:none; color: #2abd4d;" >
                    <i class="ui green checkmark icon"></i> Setting Saved
                </div>
                <div class="ui basic segment advanceoptions">
                    <div class="ui accordion advanceSettings">
                        <div class="title">
                          <i class="dropdown icon"></i>
                            Advance Settings
                        </div>
                        <div class="content">
                            <div class="ui toggle checkbox">
                                <input type="checkbox" id="enableWhitelistLoopback">
                                <label>Enable LAN and Loopback<br>
                                    <small>Allowing loopback request from your public IP address and local area network devices</small></label>
                            </div>
                        </div>
                    </div>  
                </div>
                <h4>Country Whitelist</h4>
                    <p><i class="yellow exclamation triangle icon"></i>
                    This will allow all requests from the selected country. The requester's location is estimated from their IP address and may not be 100% accurate.</p>

                <div class="ui form">
                    <div class="field">
                        <label>Select Country</label>
                        <div id="countrySelectorWhitelist" class="ui fluid search multiple selection dropdown">
                            <input type="hidden" name="country">
                            <i class="dropdown icon"></i>
                            <div class="default text">Select Country</div>
                            <div class="menu">
                            <div class="item" data-value="af"><i class="af flag"></i>Afghanistan</div>
                            <div class="item" data-value="ax"><i class="ax flag"></i>Aland Islands</div>
                            <div class="item" data-value="al"><i class="al flag"></i>Albania</div>
                            <div class="item" data-value="dz"><i class="dz flag"></i>Algeria</div>
                            <div class="item" data-value="as"><i class="as flag"></i>American Samoa</div>
                            <div class="item" data-value="ad"><i class="ad flag"></i>Andorra</div>
                            <div class="item" data-value="ao"><i class="ao flag"></i>Angola</div>
                            <div class="item" data-value="ai"><i class="ai flag"></i>Anguilla</div>
                            <div class="item" data-value="ag"><i class="ag flag"></i>Antigua</div>
                            <div class="item" data-value="ar"><i class="ar flag"></i>Argentina</div>
                            <div class="item" data-value="am"><i class="am flag"></i>Armenia</div>
                            <div class="item" data-value="aw"><i class="aw flag"></i>Aruba</div>
                            <div class="item" data-value="au"><i class="au flag"></i>Australia</div>
                            <div class="item" data-value="at"><i class="at flag"></i>Austria</div>
                            <div class="item" data-value="az"><i class="az flag"></i>Azerbaijan</div>
                            <div class="item" data-value="bs"><i class="bs flag"></i>Bahamas</div>
                            <div class="item" data-value="bh"><i class="bh flag"></i>Bahrain</div>
                            <div class="item" data-value="bd"><i class="bd flag"></i>Bangladesh</div>
                            <div class="item" data-value="bb"><i class="bb flag"></i>Barbados</div>
                            <div class="item" data-value="by"><i class="by flag"></i>Belarus</div>
                            <div class="item" data-value="be"><i class="be flag"></i>Belgium</div>
                            <div class="item" data-value="bz"><i class="bz flag"></i>Belize</div>
                            <div class="item" data-value="bj"><i class="bj flag"></i>Benin</div>
                            <div class="item" data-value="bm"><i class="bm flag"></i>Bermuda</div>
                            <div class="item" data-value="bt"><i class="bt flag"></i>Bhutan</div>
                            <div class="item" data-value="bo"><i class="bo flag"></i>Bolivia</div>
                            <div class="item" data-value="ba"><i class="ba flag"></i>Bosnia</div>
                            <div class="item" data-value="bw"><i class="bw flag"></i>Botswana</div>
                            <div class="item" data-value="bv"><i class="bv flag"></i>Bouvet Island</div>
                            <div class="item" data-value="br"><i class="br flag"></i>Brazil</div>
                            <div class="item" data-value="vg"><i class="vg flag"></i>British Virgin Islands</div>
                            <div class="item" data-value="bn"><i class="bn flag"></i>Brunei</div>
                            <div class="item" data-value="bg"><i class="bg flag"></i>Bulgaria</div>
                            <div class="item" data-value="bf"><i class="bf flag"></i>Burkina Faso</div>
                            <div class="item" data-value="mm"><i class="mm flag"></i>Burma</div>
                            <div class="item" data-value="bi"><i class="bi flag"></i>Burundi</div>
                            <div class="item" data-value="tc"><i class="tc flag"></i>Caicos Islands</div>
                            <div class="item" data-value="kh"><i class="kh flag"></i>Cambodia</div>
                            <div class="item" data-value="cm"><i class="cm flag"></i>Cameroon</div>
                            <div class="item" data-value="ca"><i class="ca flag"></i>Canada</div>
                            <div class="item" data-value="cv"><i class="cv flag"></i>Cape Verde</div>
                            <div class="item" data-value="ky"><i class="ky flag"></i>Cayman Islands</div>
                            <div class="item" data-value="cf"><i class="cf flag"></i>Central African Republic</div>
                            <div class="item" data-value="td"><i class="td flag"></i>Chad</div>
                            <div class="item" data-value="cl"><i class="cl flag"></i>Chile</div>
                            <div class="item" data-value="cn"><i class="cn flag"></i>China</div>
                            <div class="item" data-value="cx"><i class="cx flag"></i>Christmas Island</div>
                            <div class="item" data-value="cc"><i class="cc flag"></i>Cocos Islands</div>
                            <div class="item" data-value="co"><i class="co flag"></i>Colombia</div>
                            <div class="item" data-value="km"><i class="km flag"></i>Comoros</div>
                            <div class="item" data-value="cg"><i class="cg flag"></i>Congo Brazzaville</div>
                            <div class="item" data-value="cd"><i class="cd flag"></i>Congo</div>
                            <div class="item" data-value="ck"><i class="ck flag"></i>Cook Islands</div>
                            <div class="item" data-value="cr"><i class="cr flag"></i>Costa Rica</div>
                            <div class="item" data-value="ci"><i class="ci flag"></i>Cote Divoire</div>
                            <div class="item" data-value="hr"><i class="hr flag"></i>Croatia</div>
                            <div class="item" data-value="cu"><i class="cu flag"></i>Cuba</div>
                            <div class="item" data-value="cy"><i class="cy flag"></i>Cyprus</div>
                            <div class="item" data-value="cz"><i class="cz flag"></i>Czech Republic</div>
                            <div class="item" data-value="dk"><i class="dk flag"></i>Denmark</div>
                            <div class="item" data-value="dj"><i class="dj flag"></i>Djibouti</div>
                            <div class="item" data-value="dm"><i class="dm flag"></i>Dominica</div>
                            <div class="item" data-value="do"><i class="do flag"></i>Dominican Republic</div>
                            <div class="item" data-value="ec"><i class="ec flag"></i>Ecuador</div>
                            <div class="item" data-value="eg"><i class="eg flag"></i>Egypt</div>
                            <div class="item" data-value="sv"><i class="sv flag"></i>El Salvador</div>
                            <div class="item" data-value="gb"><i class="gb flag"></i>England</div>
                            <div class="item" data-value="gq"><i class="gq flag"></i>Equatorial Guinea</div>
                            <div class="item" data-value="er"><i class="er flag"></i>Eritrea</div>
                            <div class="item" data-value="ee"><i class="ee flag"></i>Estonia</div>
                            <div class="item" data-value="et"><i class="et flag"></i>Ethiopia</div>
                            <div class="item" data-value="eu"><i class="eu flag"></i>European Union</div>
                            <div class="item" data-value="fk"><i class="fk flag"></i>Falkland Islands</div>
                            <div class="item" data-value="fo"><i class="fo flag"></i>Faroe Islands</div>
                            <div class="item" data-value="fj"><i class="fj flag"></i>Fiji</div>
                            <div class="item" data-value="fi"><i class="fi flag"></i>Finland</div>
                            <div class="item" data-value="fr"><i class="fr flag"></i>France</div>
                            <div class="item" data-value="gf"><i class="gf flag"></i>French Guiana</div>
                            <div class="item" data-value="pf"><i class="pf flag"></i>French Polynesia</div>
                            <div class="item" data-value="tf"><i class="tf flag"></i>French Territories</div>
                            <div class="item" data-value="ga"><i class="ga flag"></i>Gabon</div>
                            <div class="item" data-value="gm"><i class="gm flag"></i>Gambia</div>
                            <div class="item" data-value="ge"><i class="ge flag"></i>Georgia</div>
                            <div class="item" data-value="de"><i class="de flag"></i>Germany</div>
                            <div class="item" data-value="gh"><i class="gh flag"></i>Ghana</div>
                            <div class="item" data-value="gi"><i class="gi flag"></i>Gibraltar</div>
                            <div class="item" data-value="gr"><i class="gr flag"></i>Greece</div>
                            <div class="item" data-value="gl"><i class="gl flag"></i>Greenland</div>
                            <div class="item" data-value="gd"><i class="gd flag"></i>Grenada</div>
                            <div class="item" data-value="gp"><i class="gp flag"></i>Guadeloupe</div>
                            <div class="item" data-value="gu"><i class="gu flag"></i>Guam</div>
                            <div class="item" data-value="gt"><i class="gt flag"></i>Guatemala</div>
                            <div class="item" data-value="gw"><i class="gw flag"></i>Guinea-Bissau</div>
                            <div class="item" data-value="gn"><i class="gn flag"></i>Guinea</div>
                            <div class="item" data-value="gy"><i class="gy flag"></i>Guyana</div>
                            <div class="item" data-value="ht"><i class="ht flag"></i>Haiti</div>
                            <div class="item" data-value="hm"><i class="hm flag"></i>Heard Island</div>
                            <div class="item" data-value="hn"><i class="hn flag"></i>Honduras</div>
                            <div class="item" data-value="hk"><i class="hk flag"></i>Hong Kong</div>
                            <div class="item" data-value="hu"><i class="hu flag"></i>Hungary</div>
                            <div class="item" data-value="is"><i class="is flag"></i>Iceland</div>
                            <div class="item" data-value="in"><i class="in flag"></i>India</div>
                            <div class="item" data-value="io"><i class="io flag"></i>Indian Ocean Territory</div>
                            <div class="item" data-value="id"><i class="id flag"></i>Indonesia</div>
                            <div class="item" data-value="ir"><i class="ir flag"></i>Iran</div>
                            <div class="item" data-value="iq"><i class="iq flag"></i>Iraq</div>
                            <div class="item" data-value="ie"><i class="ie flag"></i>Ireland</div>
                            <div class="item" data-value="il"><i class="il flag"></i>Israel</div>
                            <div class="item" data-value="it"><i class="it flag"></i>Italy</div>
                            <div class="item" data-value="jm"><i class="jm flag"></i>Jamaica</div>
                            <div class="item" data-value="jp"><i class="jp flag"></i>Japan</div>
                            <div class="item" data-value="jo"><i class="jo flag"></i>Jordan</div>
                            <div class="item" data-value="kz"><i class="kz flag"></i>Kazakhstan</div>
                            <div class="item" data-value="ke"><i class="ke flag"></i>Kenya</div>
                            <div class="item" data-value="ki"><i class="ki flag"></i>Kiribati</div>
                            <div class="item" data-value="kw"><i class="kw flag"></i>Kuwait</div>
                            <div class="item" data-value="kg"><i class="kg flag"></i>Kyrgyzstan</div>
                            <div class="item" data-value="la"><i class="la flag"></i>Laos</div>
                            <div class="item" data-value="lv"><i class="lv flag"></i>Latvia</div>
                            <div class="item" data-value="lb"><i class="lb flag"></i>Lebanon</div>
                            <div class="item" data-value="ls"><i class="ls flag"></i>Lesotho</div>
                            <div class="item" data-value="lr"><i class="lr flag"></i>Liberia</div>
                            <div class="item" data-value="ly"><i class="ly flag"></i>Libya</div>
                            <div class="item" data-value="li"><i class="li flag"></i>Liechtenstein</div>
                            <div class="item" data-value="lt"><i class="lt flag"></i>Lithuania</div>
                            <div class="item" data-value="lu"><i class="lu flag"></i>Luxembourg</div>
                            <div class="item" data-value="mo"><i class="mo flag"></i>Macau</div>
                            <div class="item" data-value="mk"><i class="mk flag"></i>North Macedonia</div>
                            <div class="item" data-value="mg"><i class="mg flag"></i>Madagascar</div>
                            <div class="item" data-value="mw"><i class="mw flag"></i>Malawi</div>
                            <div class="item" data-value="my"><i class="my flag"></i>Malaysia</div>
                            <div class="item" data-value="mv"><i class="mv flag"></i>Maldives</div>
                            <div class="item" data-value="ml"><i class="ml flag"></i>Mali</div>
                            <div class="item" data-value="mt"><i class="mt flag"></i>Malta</div>
                            <div class="item" data-value="mh"><i class="mh flag"></i>Marshall Islands</div>
                            <div class="item" data-value="mq"><i class="mq flag"></i>Martinique</div>
                            <div class="item" data-value="mr"><i class="mr flag"></i>Mauritania</div>
                            <div class="item" data-value="mu"><i class="mu flag"></i>Mauritius</div>
                            <div class="item" data-value="yt"><i class="yt flag"></i>Mayotte</div>
                            <div class="item" data-value="mx"><i class="mx flag"></i>Mexico</div>
                            <div class="item" data-value="fm"><i class="fm flag"></i>Micronesia</div>
                            <div class="item" data-value="md"><i class="md flag"></i>Moldova</div>
                            <div class="item" data-value="mc"><i class="mc flag"></i>Monaco</div>
                            <div class="item" data-value="mn"><i class="mn flag"></i>Mongolia</div>
                            <div class="item" data-value="me"><i class="me flag"></i>Montenegro</div>
                            <div class="item" data-value="ms"><i class="ms flag"></i>Montserrat</div>
                            <div class="item" data-value="ma"><i class="ma flag"></i>Morocco</div>
                            <div class="item" data-value="mz"><i class="mz flag"></i>Mozambique</div>
                            <div class="item" data-value="na"><i class="na flag"></i>Namibia</div>
                            <div class="item" data-value="nr"><i class="nr flag"></i>Nauru</div>
                            <div class="item" data-value="np"><i class="np flag"></i>Nepal</div>
                            <div class="item" data-value="an"><i class="an flag"></i>Netherlands Antilles</div>
                            <div class="item" data-value="nl"><i class="nl flag"></i>Netherlands</div>
                            <div class="item" data-value="nc"><i class="nc flag"></i>New Caledonia</div>
                            <div class="item" data-value="pg"><i class="pg flag"></i>New Guinea</div>
                            <div class="item" data-value="nz"><i class="nz flag"></i>New Zealand</div>
                            <div class="item" data-value="ni"><i class="ni flag"></i>Nicaragua</div>
                            <div class="item" data-value="ne"><i class="ne flag"></i>Niger</div>
                            <div class="item" data-value="ng"><i class="ng flag"></i>Nigeria</div>
                            <div class="item" data-value="nu"><i class="nu flag"></i>Niue</div>
                            <div class="item" data-value="nf"><i class="nf flag"></i>Norfolk Island</div>
                            <div class="item" data-value="kp"><i class="kp flag"></i>North Korea</div>
                            <div class="item" data-value="mp"><i class="mp flag"></i>Northern Mariana Islands</div>
                            <div class="item" data-value="no"><i class="no flag"></i>Norway</div>
                            <div class="item" data-value="om"><i class="om flag"></i>Oman</div>
                            <div class="item" data-value="pk"><i class="pk flag"></i>Pakistan</div>
                            <div class="item" data-value="pw"><i class="pw flag"></i>Palau</div>
                            <div class="item" data-value="ps"><i class="ps flag"></i>Palestine</div>
                            <div class="item" data-value="pa"><i class="pa flag"></i>Panama</div>
                            <div class="item" data-value="py"><i class="py flag"></i>Paraguay</div>
                            <div class="item" data-value="pe"><i class="pe flag"></i>Peru</div>
                            <div class="item" data-value="ph"><i class="ph flag"></i>Philippines</div>
                            <div class="item" data-value="pn"><i class="pn flag"></i>Pitcairn Islands</div>
                            <div class="item" data-value="pl"><i class="pl flag"></i>Poland</div>
                            <div class="item" data-value="pt"><i class="pt flag"></i>Portugal</div>
                            <div class="item" data-value="pr"><i class="pr flag"></i>Puerto Rico</div>
                            <div class="item" data-value="qa"><i class="qa flag"></i>Qatar</div>
                            <div class="item" data-value="re"><i class="re flag"></i>Reunion</div>
                            <div class="item" data-value="ro"><i class="ro flag"></i>Romania</div>
                            <div class="item" data-value="ru"><i class="ru flag"></i>Russia</div>
                            <div class="item" data-value="rw"><i class="rw flag"></i>Rwanda</div>
                            <div class="item" data-value="sh"><i class="sh flag"></i>Saint Helena</div>
                            <div class="item" data-value="kn"><i class="kn flag"></i>Saint Kitts and Nevis</div>
                            <div class="item" data-value="lc"><i class="lc flag"></i>Saint Lucia</div>
                            <div class="item" data-value="pm"><i class="pm flag"></i>Saint Pierre</div>
                            <div class="item" data-value="vc"><i class="vc flag"></i>Saint Vincent</div>
                            <div class="item" data-value="ws"><i class="ws flag"></i>Samoa</div>
                            <div class="item" data-value="sm"><i class="sm flag"></i>San Marino</div>
                            <div class="item" data-value="gs"><i class="gs flag"></i>Sandwich Islands</div>
                            <div class="item" data-value="st"><i class="st flag"></i>Sao Tome</div>
                            <div class="item" data-value="sa"><i class="sa flag"></i>Saudi Arabia</div>
                            <div class="item" data-value="sn"><i class="sn flag"></i>Senegal</div>
                            <div class="item" data-value="cs"><i class="cs flag"></i>Serbia</div>
                            <div class="item" data-value="rs"><i class="rs flag"></i>Serbia</div>
                            <div class="item" data-value="sc"><i class="sc flag"></i>Seychelles</div>
                            <div class="item" data-value="sl"><i class="sl flag"></i>Sierra Leone</div>
                            <div class="item" data-value="sg"><i class="sg flag"></i>Singapore</div>
                            <div class="item" data-value="sk"><i class="sk flag"></i>Slovakia</div>
                            <div class="item" data-value="si"><i class="si flag"></i>Slovenia</div>
                            <div class="item" data-value="sb"><i class="sb flag"></i>Solomon Islands</div>
                            <div class="item" data-value="so"><i class="so flag"></i>Somalia</div>
                            <div class="item" data-value="za"><i class="za flag"></i>South Africa</div>
                            <div class="item" data-value="kr"><i class="kr flag"></i>South Korea</div>
                            <div class="item" data-value="es"><i class="es flag"></i>Spain</div>
                            <div class="item" data-value="lk"><i class="lk flag"></i>Sri Lanka</div>
                            <div class="item" data-value="sd"><i class="sd flag"></i>Sudan</div>
                            <div class="item" data-value="sr"><i class="sr flag"></i>Suriname</div>
                            <div class="item" data-value="sj"><i class="sj flag"></i>Svalbard</div>
                            <div class="item" data-value="sz"><i class="sz flag"></i>Swaziland</div>
                            <div class="item" data-value="se"><i class="se flag"></i>Sweden</div>
                            <div class="item" data-value="ch"><i class="ch flag"></i>Switzerland</div>
                            <div class="item" data-value="sy"><i class="sy flag"></i>Syria</div>
                            <div class="item" data-value="tw"><i class="tw flag"></i>Taiwan</div>
                            <div class="item" data-value="tj"><i class="tj flag"></i>Tajikistan</div>
                            <div class="item" data-value="tz"><i class="tz flag"></i>Tanzania</div>
                            <div class="item" data-value="th"><i class="th flag"></i>Thailand</div>
                            <div class="item" data-value="tl"><i class="tl flag"></i>Timorleste</div>
                            <div class="item" data-value="tg"><i class="tg flag"></i>Togo</div>
                            <div class="item" data-value="tk"><i class="tk flag"></i>Tokelau</div>
                            <div class="item" data-value="to"><i class="to flag"></i>Tonga</div>
                            <div class="item" data-value="tt"><i class="tt flag"></i>Trinidad</div>
                            <div class="item" data-value="tn"><i class="tn flag"></i>Tunisia</div>
                            <div class="item" data-value="tr"><i class="tr flag"></i>Turkey</div>
                            <div class="item" data-value="tm"><i class="tm flag"></i>Turkmenistan</div>
                            <div class="item" data-value="tv"><i class="tv flag"></i>Tuvalu</div>
                            <div class="item" data-value="ug"><i class="ug flag"></i>Uganda</div>
                            <div class="item" data-value="ua"><i class="ua flag"></i>Ukraine</div>
                            <div class="item" data-value="ae"><i class="ae flag"></i>United Arab Emirates</div>
                            <div class="item" data-value="us"><i class="us flag"></i>United States</div>
                            <div class="item" data-value="uy"><i class="uy flag"></i>Uruguay</div>
                            <div class="item" data-value="um"><i class="um flag"></i>Us Minor Islands</div>
                            <div class="item" data-value="vi"><i class="vi flag"></i>Us Virgin Islands</div>
                            <div class="item" data-value="uz"><i class="uz flag"></i>Uzbekistan</div>
                            <div class="item" data-value="vu"><i class="vu flag"></i>Vanuatu</div>
                            <div class="item" data-value="va"><i class="va flag"></i>Vatican City</div>
                            <div class="item" data-value="ve"><i class="ve flag"></i>Venezuela</div>
                            <div class="item" data-value="vn"><i class="vn flag"></i>Vietnam</div>
                            <div class="item" data-value="wf"><i class="wf flag"></i>Wallis and Futuna</div>
                            <div class="item" data-value="eh"><i class="eh flag"></i>Western Sahara</div>
                            <div class="item" data-value="ye"><i class="ye flag"></i>Yemen</div>
                            <div class="item" data-value="zm"><i class="zm flag"></i>Zambia</div>
                            <div class="item" data-value="zw"><i class="zw flag"></i>Zimbabwe</div>
                        </div>
                        </div>
                    </div>
                    <button class="ui basic green button" id="whitelist-btn" onclick="addCountryToWhitelist();"><i class="ui green add icon"></i> Whitelist Country</button>
                </div>
                <table class="ui unstackable basic celled table">
                    <thead>
                        <tr>
                            <th>ISO Code</th>
                            <th>Remove</th>
                        </tr>
                    </thead>
                    <tbody id="whitelistCountryList">

                    </tbody>
                </table>

                <h4>IP Whitelist</h4>
                <p>Whitelist a certain IP or IP range</p>
                <div class="ui form">
                    <div class="field">
                        <label>IP Address</label>
                        <input id="ipAddressInputWhitelist" type="text" placeholder="IP Address">
                    </div>
                    <div class="field">
                        <label>Remarks (Optional)</label>
                        <input id="ipAddressCommentsWhitelist" type="text" placeholder="Comments or remarks for this IP range">
                    </div>
                    <button id="addIpButton" onclick="addIpWhitelist();" class="ui basic green button">
                        <i class="green add icon"></i> Whitelist IP
                    </button>
                </div>
                <div class="ui message">
                    <i class="ui info circle icon"></i> IP Address support the following formats
                    <div class="ui bulleted list">
                        <div class="item">Fixed IP Address (e.g. 192.128.4.100 or fe80::210:5aff:feaa:20a2)</div>
                        <div class="item">IP Wildcard (e.g. 172.164.*.*)</div>
                        <div class="item">CIDR String (e.g. 128.32.0.1/16)</div>
                    </div>
                </div>
                <table class="ui unstackable basic celled table">
                    <thead>
                    <tr>
                        <th>IP Address</th>
                        <th>Remarks</th>
                        <th>Remove</th>
                    </tr>
                    </thead>
                    <tbody id="whitelistIpTable">

                    </tbody>
                </table>
            </div>
            <!-- Quick ban list-->
            <div class="ui bottom attached tab segment" data-tab="tab_quickban">
                <h2>Quick Ban List</h2>
                <button style="margin-top: -1em;" onclick="initBlacklistQuickBanTable();" class="ui green small right floated circular basic icon button"><i class="ui refresh icon"></i></button>
                <p>You can perform one-click IP ban on the list below if you observe unusual traffic from an unknown origin<br>
                Blacklist must be enabled in order to use this feature.</p>
                <div class="ui divider"></div>
                <table class="ui celled unstackable very compact table" id="ipTable">
                    <thead>
                        <tr>
                        <th>IP</th>
                        <th>Access Count</th>
                        <th>Country of Origin</th>
                        <th>Blacklist</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                <div class="pagination"></div>
            </div>
        </div>  
    </div>
</div>
<script>
    /*
        Access Control
    */
   var currentEditingAccessRule = "default"; //ID of the current editing access rule
   var currentListOfAccessRules = [];
  
    $(".dropdown").dropdown();
    $('.menu .accesscontrol.item').tab();
    $('.menu .accesscontrol.item').addClass("activated");

    /* Access Rule Selector */
    function openAccessRuleEditor(){
        showSideWrapper('snippet/accessRuleEditor.html');
    }

    function reloadAccessRulesWithFeedback(){
        reloadAccessRules(function(){
            msgbox("Access Rules Reloaded", true);
        });
    }
    
    function reloadAccessRules(callback=undefined){
        initAccessRuleList(function(){
            //Check if the previous access rule is still there
            let stillExists = false;
            for (var i = 0; i < currentListOfAccessRules.length; i++){
                let thisAccessRule = currentListOfAccessRules[i];
                if (thisAccessRule.ID == currentEditingAccessRule){
                    stillExists = true;
                    break;
                }
            }

            if (stillExists){
                handleSelectedAccessRuleChange(currentEditingAccessRule);
                $("#accessRuleSelector").dropdown("set selected", currentEditingAccessRule);
            }else{
                handleSelectedAccessRuleChange("default");
                $("#accessRuleSelector").dropdown("set selected", "default");
            }

            if (callback != undefined){
                callback();
            }
            
        });
    }

    function initAccessRuleList(callback=undefined){
        $.get("/api/access/list", function(data){
            if (data.error == undefined){
                $("#accessRuleList").html("");
                data.forEach(function(rule){
                    let icon = `<i class="ui grey filter icon"></i>`;
                    if (rule.ID == "default"){
                        icon = `<i class="ui yellow star icon"></i>`;
                    }else if (rule.BlacklistEnabled && !rule.WhitelistEnabled){
                        //This is a blacklist filter
                        icon = `<i class="ui red filter icon"></i>`;
                    }else if (rule.WhitelistEnabled && !rule.BlacklistEnabled){
                        //This is a whitelist filter
                        icon = `<i class="ui green filter icon"></i>`;
                    }
                    $("#accessRuleList").append(`<div class="item" data-value="${rule.ID}">${icon} ${rule.Name}</div>`);
                });
                currentListOfAccessRules = data;
                $(".dropdown").dropdown();
                if (callback != undefined){
                    callback();
                }
            }else{
                msgbox("Access rule load failed: " + data.error, false);
            }
        })
    }

    //Load default when the page is first loaded
    initAccessRuleList(function(){
        $("#accessRuleSelector").dropdown("set selected", "default");
        for (var i = 0; i < currentListOfAccessRules.length; i++){
            let thisAccessRule = currentListOfAccessRules[i];
            if (thisAccessRule.ID == "default"){
                $("#currentEditingAccessRule").html(`Editing Access Rule: ${thisAccessRule.Name} <span style="font-weight: 300;">[${thisAccessRule.ID}]</span>`);
                $("#accessRuleDesc").text(thisAccessRule.Desc);
                break;
            }
        }
        initBlackWhitelistTables();
    });

    //On dropdown change on access rule selection
    function handleSelectedAccessRuleChange(newRuleUUID){
        currentEditingAccessRule = newRuleUUID;
        //Load the name and desc of this acess rule
        let name = "";
        let desc = "";
        for (var i = 0; i < currentListOfAccessRules.length; i++){
            let thisAccessRule = currentListOfAccessRules[i];
            if (thisAccessRule.ID == newRuleUUID){
                name = thisAccessRule.Name;
                desc = thisAccessRule.Desc;
                break;
            }
        }
        $("#currentEditingAccessRule").html(`Editing Access Rule: ${name} <span style="font-weight: 300;">[${newRuleUUID}]</span>`);
        $("#accessRuleDesc").text(desc);

        initBlackWhitelistTables();
    }
    
    //Load all the black white lists
    function initBlackWhitelistTables(){
        //Remove event listener on both toggle buttons
        $("#enableWhitelist").off("change");
        $("#enableBlacklist").off("change");

        //Initialize the button states
        initBlacklistEnableState();
        initWhitelistEnableState();

        //Update the lists
        initBannedCountryList();
        initIpBanTable()
        initWhitelistCountryList();
        initIpWhitelistTable();
    }

    /*
        Table Init
    */

    //Blacklist country table
    function initBannedCountryList(){
        $.get("/api/blacklist/list?type=country&id=" + currentEditingAccessRule, function(data) {
            let bannedListHtml = '';

            //Check if the country code list contains all eu countries. If yes, replace it with "EU"
            let allEu = true;
            let euCountries = getEUCCs();
            for (var i = 0; i < euCountries.length; i++){
                if (!data.includes(euCountries[i])){
                    allEu = false;
                    break;
                }
            }

            if (allEu){
                //Remove EU countries from the list and replace it with EU
                data = data.filter(function(value, index, arr){
                    return !euCountries.includes(value);
                });
                data.push("eu");
            }

            data.forEach((countryCode) => {
                bannedListHtml += `
                <tr>
                    <td><i class="${countryCode} flag"></i> ${getCountryName(countryCode)} (${countryCode.toUpperCase()})</td>
                    <td><button class="ui red basic mini icon button" onclick="removeFromBannedList('${countryCode}')"><i class="trash icon"></i></button></td>
                </tr>
                `;
            });
            $('#banned-list').html(bannedListHtml);
            filterCountries(data, "#countrySelector .menu .item");
            if (data.length === 0) {
                $('#banned-list').append(`
                    <tr>
                        <td colspan="2">
                            <i class="green check circle icon"></i>
                            There are no blacklisted countries
                        </td>
                    </tr>
                `);
            }

        });
    }

    //Blacklist ip table
    function initIpBanTable(){
        $.get('/api/blacklist/list?type=ip&id=' + currentEditingAccessRule, function(data) {
            $('#blacklistIpTable').html("");
            if (data.length === 0) {
                $('#blacklistIpTable').append(`
                <tr>
                    <td colspan="2"><i class="green check circle icon"></i>There are no blacklisted IP addresses</td>
                </tr>
                `);
            } else {
                $.each(data, function(index, ip) {
                    let icon = "globe icon";
                    if (isLAN(ip)){
                        icon = "desktop icon";
                    }else if (isHomeAddr(ip)){
                        icon = "home icon";
                    }
                    $('#blacklistIpTable').append(`
                        <tr class="blacklistItem" ip="${encodeURIComponent(ip)}">
                            <td><i class="${icon}"></i> ${ip}</td>
                            <td><button class="ui icon basic mini red button" onclick="removeIpBlacklist('${ip}');"><i class="trash alternate icon"></i></button></td>
                        </tr>
                    `);
                });
            }

            initBlacklistQuickBanTable();
        });
    }


    //Init blacklist state
    function initBlacklistEnableState(){
        $.get('/api/blacklist/enable?id=' + currentEditingAccessRule, function(data){
            if (data == true){
                $('#enableBlacklist').parent().checkbox("set checked");
                $("#ipTable").removeClass("disabled");
            }else{
                $('#enableBlacklist').parent().checkbox("set unchecked");
                $("#ipTable").addClass("disabled");
            }

            //Register on change event
            $("#enableBlacklist").off("change").on("change", function(){
                enableBlacklist();
            })
        });
    }
    

    //Whitelist country table
    function initWhitelistCountryList(){
        $.get("/api/whitelist/list?type=country&id=" + currentEditingAccessRule, function(data) {
            let whiteListHTML = '';
            
            //Check if the country code list contains all eu countries. If yes, replace it with "EU"
            let allEu = true;
            let euCountries = getEUCCs();
            let countryCodesIndata = data.map(function(item){
                //data[n].CC is the country code 
                return item.CC;
            });
            for (var i = 0; i < euCountries.length; i++){
                if (!countryCodesIndata.includes(euCountries[i])){
                    allEu = false;
                    break;
                }
            }

            if (allEu){
                //Remove EU countries from the list and replace it with EU
                data = data.filter(function(value, index, arr){
                    return !euCountries.includes(value.CC);
                });
                data.push({
                    CC: "eu"
                });
            }
            
            data.forEach((countryWhitelistEntry) => {
                let countryCode = countryWhitelistEntry.CC;
                whiteListHTML += `
                <tr>
                    <td><i class="${countryCode} flag"></i> ${getCountryName(countryCode)} (${countryCode.toUpperCase()})</td>
                    <td><button class="ui red basic mini icon button" onclick="removeFromWhiteList('${countryCode}')"><i class="trash icon"></i></button></td>
                </tr>
                `;
            });
            $('#whitelistCountryList').html(whiteListHTML);

            //Map the data.CC to the country code
            let countryCodes = data.map(function(item){
                return item.CC;
            });
            filterCountries(countryCodes, "#countrySelectorWhitelist .menu .item");
            if (data.length === 0) {
                $('#whitelistCountryList').append(`
                    <tr>
                        <td colspan="2">
                            <i class="green check circle icon"></i>
                            There are no whitelisted countries
                        </td>
                    </tr>
                `);
            }

        });
    }
    

    //Whitelist ip table
    function initIpWhitelistTable(){
        $.get('/api/whitelist/list?type=ip&id=' + currentEditingAccessRule, function(data) {
            $('#whitelistIpTable').html("");
            if (data.length === 0) {
                $('#whitelistIpTable').append(`
                <tr>
                    <td colspan="3"><i class="green check circle icon"></i>There are no whitelisted IP addresses</td>
                </tr>
                `);
            } else {
                $.each(data, function(index, ipEntry) {
                    let ip = ipEntry.IP;
                    let icon = "globe icon";
                    if (isLAN(ip)){
                        icon = "desktop icon";
                    }else if (isHomeAddr(ip)){
                        icon = "home icon";
                    }
                    $('#whitelistIpTable').append(`
                        <tr class="whitelistItem" ip="${encodeURIComponent(ip)}">
                            <td><i class="${icon}"></i> ${ip}</td>
                            <td>${ipEntry.Comment}</td>
                            <td><button class="ui icon basic mini red button" onclick="removeIpWhitelist('${ip}');"><i class="trash alternate icon"></i></button></td>
                        </tr>
                    `);
                });
            }

        });
    }
    

    //Init whitelist state
    function initWhitelistEnableState(){
        $.get('/api/whitelist/enable?id=' + currentEditingAccessRule, function(data){
            if (data == true){
                $('#enableWhitelist').parent().checkbox("set checked");
            }else{
                $('#enableWhitelist').parent().checkbox("set unchecked");
            }

            //Register on change event
            $("#enableWhitelist").off("change").on("change", function(){
                enableWhitelist();
            })
        });

        $.get("/api/whitelist/allowLocal?id=" + currentEditingAccessRule, function(data){
            if (data == true){
                $('#enableWhitelistLoopback').parent().checkbox("set checked");
            }else{
                $('#enableWhitelistLoopback').parent().checkbox("set unchecked");
            }

            //Register on change event
            $("#enableWhitelistLoopback").off("change").on("change", function(){
                enableWhitelistLoopback();
            })
        });
    }
    
    function enableWhitelistLoopback(){
        var isChecked = $('#enableWhitelistLoopback').is(':checked');
        $.cjax({
            type: 'POST',
            url: '/api/whitelist/allowLocal',
            data: { enable: isChecked, id: currentEditingAccessRule},
            success: function(data){
                if (data.error != undefined){
                    msgbox("Failed to update loopback whitelist: " + data.error, false);
                    //Revert the checkbox state
                    if (isChecked){
                        $('#enableWhitelistLoopback').parent().checkbox("set unchecked");
                    }else{
                        $('#enableWhitelistLoopback').parent().checkbox("set checked");
                    }
                    return;
                }else{
                    msgbox("Loopback whitelist " + (isChecked ? "enabled" : "disabled"), true);
                }
                
            }
        });
    }
    
    /*
        Blacklist API Calls
    */
    function enableBlacklist() {
        var isChecked = $('#enableBlacklist').is(':checked');
        $.cjax({
            type: 'POST',
            url: '/api/blacklist/enable',
            data: { enable: isChecked, id: currentEditingAccessRule},
            success: function(data){
                if (isChecked){
                    $("#ipTable").removeClass("disabled");
                }else{
                    $("#ipTable").addClass("disabled");
                }
                
                $(".toggleSucc").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
            }
        });
    }

    function getEUCCs(){
        return ["at","be","bg","cy","cz","de","dk","ee","es","fi","fr","gr","hr","hu","ie","it","lt","lu","lv","mt","nl","pl","pt","se","si","sk"];
    }

    function addCountryToBlacklist() {
        var countryCode = $("#countrySelector").dropdown("get value").toLowerCase();
        let ccs = [countryCode];
        if (countryCode.includes(",")){
            //Multiple country codes selected
            //Usually just a few countries a for loop will get the job done
            ccs = countryCode.split(",");
        }

        //If the ccs includes "eu", remove the "eu" and add all eu country code to the list
        if (ccs.includes("eu")){
            ccs = ccs.concat(getEUCCs());
            ccs = ccs.filter(function(item){
                return item != "eu";
            });
        }

        let counter = ccs.length;
        $.cjax({
            type: "POST",
            url: "/api/blacklist/country/add",
            method: "POST",
            data: { cc: ccs.join(","), id: currentEditingAccessRule},
            success: function(response) {
                if (response.error != undefined){
                    msgbox(response.error, false);
                }
                initBannedCountryList();
                if (ccs.length == 1){
                    //Single country
                    msgbox(`Added ${getCountryName(ccs[0])} to blacklist`);
                }else{
                    msgbox(ccs.length + " countries added to blacklist");
                }
            },
            error: function(xhr, status, error) {
            // handle error response
            }
        });
        $('#countrySelector').dropdown('clear');
    }

    function removeFromBannedList(countryCode){
        let countryName = getCountryName(countryCode);
        if (countryCode == "eu"){
            let euCountries = getEUCCs();
            countryCode = euCountries.join(",");
            countryName = "European Union";
        }else{
            countryCode = countryCode.toLowerCase();
        }
        
        
        $.cjax({
            url: "/api/blacklist/country/remove",
            method: "POST",
            data: { cc: countryCode, id: currentEditingAccessRule},
            success: function(response) {
                if (response.error != undefined){
                    msgbox(response.error, false);
                }else{
                    msgbox(countryName + " removed from blacklist");
                }
                initBannedCountryList();
            },
            error: function(xhr, status, error) {
                console.error("Error removing country from blacklist: " + error);
                // Handle error response
            }
        });
    }

    function addIpBlacklist(){
        let targetIp = $("#ipAddressInput").val().trim();
        if (targetIp == ""){
            alert("IP address is empty")
            return
        }
        if (!isValidIpFilter(targetIp)){
            if (!confirm("This doesn't seems like a valid IP address. Continue anyway?")){
                return;
            }
        }

        $.cjax({
            url: "/api/blacklist/ip/add",
            type: "POST",
            data: {ip: targetIp.toLowerCase(), id: currentEditingAccessRule},
            success: function(response) {
                if (response.error !== undefined) {
                    msgbox(response.error, false, 6000);
                } else {
                    initIpBanTable();
                }

                $("#ipAddressInput").val("");
                $("#ipAddressInput").parent().removeClass("error");
            },
            error: function() {
                alert("Failed to add IP address to blacklist");
            }
        });
    }

    function removeIpBlacklist(ipaddr){
        //if (confirm("Confirm remove blacklist for " + ipaddr + " ?")){
            $.cjax({
                url: "/api/blacklist/ip/remove",
                type: "POST",
                data: {ip: ipaddr.toLowerCase(), id: currentEditingAccessRule},
                success: function(response) {
                    if (response.error !== undefined) {
                        msgbox(response.error, false, 6000);
                    } else {
                        initIpBanTable();
                    }
                },
                error: function() {
                    alert("Failed to remove IP address from blacklist");
                }
                
            });
        //}
    }

    /* 
        Whitelist APIs
    */
    function enableWhitelist() {
        var isChecked = $('#enableWhitelist').is(':checked');
        $.cjax({
            type: 'POST',
            url: '/api/whitelist/enable',
            data: { enable: isChecked , id: currentEditingAccessRule},
            success: function(data){
                $(".toggleSucc").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
            }
        });
    }

    function addCountryToWhitelist() {
        var countryCode = $("#countrySelectorWhitelist").dropdown("get value").toLowerCase();
        let ccs = [countryCode];
        if (countryCode.includes(",")){
            //Multiple country codes selected
            //Usually just a few countries a for loop will get the job done
            ccs = countryCode.split(",");
        }

        //If the ccs includes "eu", remove the "eu" and add all eu country code to the list
        if (ccs.includes("eu")){
            ccs = ccs.filter(function(item){
                return item != "eu";
            });
            ccs = ccs.concat(getEUCCs());
        }

        let counter = ccs.length;
        $.cjax({
            type: "POST",
            url: "/api/whitelist/country/add",
            data: { cc: ccs.join(",") , id: currentEditingAccessRule},
            success: function(response) {
                if (response.error != undefined){
                    msgbox(response.error, false);
                }

                initWhitelistCountryList();
                if (ccs.length == 1){
                    //Single country
                    msgbox(`Added ${getCountryName(ccs[0])} to whitelist`);
                }else{
                    msgbox(ccs.length + " countries added to whitelist");
                }
            },
            error: function(xhr, status, error) {
                // handle error response
            }
        });
        

        $('#countrySelectorWhitelist').dropdown('clear');
    }

    //Remove from whitelist, accepts a country code or "eu" for all EU countries
    function removeFromWhiteList(countryCode, skipConfirm = true){
        let countryName = getCountryName(countryCode);
        if (countryCode == "eu"){
            let euCountries = getEUCCs();
            countryCode = euCountries.join(",");
            countryName = "European Union";
        }else{
            countryCode = countryCode.toLowerCase(); 
        }
        if (skipConfirm || confirm("Confirm removing " + getCountryName(countryCode) + " from whitelist?")){
            $.cjax({
                url: "/api/whitelist/country/remove",
                method: "POST",
                data: { cc: countryCode , id: currentEditingAccessRule},
                success: function(response) {
                    if (response.error != undefined){
                        msgbox(response.error, false);
                    }
                    msgbox(countryName + " removed from whitelist");
                    initWhitelistCountryList();
                },
                error: function(xhr, status, error) {
                    console.error("Error removing country from blacklist: " + error);
                    // Handle error response
                }
            });
        }
    }

    function addIpWhitelist(){
        let targetIp = $("#ipAddressInputWhitelist").val().trim();
        let remarks = $("#ipAddressCommentsWhitelist").val().trim();
        if (targetIp == ""){
            alert("IP address is empty")
            return
        }
        if (!isValidIpFilter(targetIp)){
            if (!confirm("This doesn't seems like a valid IP address. Continue anyway?")){
                return;
            }
        }

        $.cjax({
            url: "/api/whitelist/ip/add",
            type: "POST",
            data: {ip: targetIp.toLowerCase(), "comment": remarks, id: currentEditingAccessRule},
            success: function(response) {
                if (response.error !== undefined) {
                    msgbox(response.error, false, 6000);
                } else {
                    initIpWhitelistTable();
                }

                $("#ipAddressInputWhitelist").val("");
                $("#ipAddressCommentsWhitelist").val("");
                $("#ipAddressInputWhitelist").parent().removeClass("error");
            },
            error: function() {
                alert("Failed to add IP address to whitelist");
            }
        });
    }

    function removeIpWhitelist(ipaddr){
        //if (confirm("Confirm remove whitelist for " + ipaddr + " ?")){
            $.cjax({
                url: "/api/whitelist/ip/remove",
                type: "POST",
                data: {ip: ipaddr.toLowerCase(), id: currentEditingAccessRule},
                success: function(response) {
                    if (response.error !== undefined) {
                        msgbox(response.error, false, 6000);
                    } else {
                        initIpWhitelistTable();
                    }
                },
                error: function() {
                    alert("Failed to remove IP address from whitelist");
                }
                
            });
        //}
    }

    /*
        Common Utilities
    */
    function filterCountries(alreadySelectedCCs, selector="#countrySelector .menu .item") {
        // get all items in the dropdown
        const items = document.querySelectorAll(selector);
        const euCountries = getEUCCs();
        //Replce "eu" in alreadySelectedCCs with all EU countries
        if (alreadySelectedCCs.includes("eu")){
            alreadySelectedCCs = alreadySelectedCCs.filter(function(item){
                return item != "eu";
            });
            alreadySelectedCCs = alreadySelectedCCs.concat(euCountries);
        }
        
        // loop through all items
        items.forEach(item => {
            // get the value of the item (i.e. the country code)
            const code = item.dataset.value;
            if (alreadySelectedCCs.includes(code)) {
                //This country code already selected. Hide it
                item.style.display = 'none';
            } else {
                // otherwise, show the item
                item.style.display = 'block';
            }
        });
    }

    //Get the country name from the dropdown
    function getCountryName(countryCode) {
        return $('#countrySelector .item[data-value="' + countryCode.toLowerCase() + '"]').text().trim();
    }

    //Check if a input is a valid IP address, wildcard of a IP address or a CIDR string
    function isValidIpFilter(input) {
        // Check if input is a valid IPv4 address
        const isValidIPv4 = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/.test(input);

        if (isValidIPv4) {
            return true;
        }

        // Check if input is a valid IPv4 wildcard address
        const isValidIPv4Wildcard = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|\*|\*\/[0-9]|[01]?[0-9]?[0-9]-[01]?[0-9]?[0-9]|\[\d+,\d+\])\.([01]?[0-9]?[0-9]|\*|\*\/[0-9]|[01]?[0-9]?[0-9]-[01]?[0-9]?[0-9]|\[\d+,\d+\])\.([01]?[0-9]?[0-9]|\*|\*\/[0-9]|[01]?[0-9]?[0-9]-[01]?[0-9]?[0-9]|\[\d+,\d+\])$/.test(input);

        if (isValidIPv4Wildcard) {
            return true;
        }

        // Check if input is a valid IPv4 CIDR address
        const isValidIPv4CIDR = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\/([0-9]|[1-2][0-9]|3[0-2])$/.test(input);

        if (isValidIPv4CIDR) {
            return true;
        }


        // Check if input is loopback ipv6
        if (input == "::1"){
            return true;
        }

        // Check if input is a valid IPv6 address
        const isValidIPv6 = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(input);

        if (isValidIPv6) {
            return true;
        }   

        //Pure magic, I have no idea how this works
        //src: https://stackoverflow.com/questions/70348674/alternate-solution-validate-ipv4-and-ipv6-with-wildcard-characters-using-r
        function evalIp6(t){var e=t.split(":"),n=t.split("::").length-1;if(8<e.length&&(9!=t.split(":").length||""!=e[e.length-1]||1!=n))return!1;if(1<n)return!1;if(-1!=t.indexOf("::*")||-1!=t.indexOf("*::"))return!1;var r=!1;for(let t=0;t<e.length;t++){if(!isIPV6Group(e[t]))return!1;"*"==e[t]&&(r=!0)}return!(!r&&0==n&&8!=e.length)}function isIPV6Group(t){var e="^(([0-9A-Fa-f]{1,4})|\\*|)$";return(e=new RegExp(e)).test(t)}
        if (evalIp6(input)){
            return true;
        }


        // Check if input is a valid IPv6 CIDR address
        const isValidIPv6CIDR = /^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/.test(input);
        if (isValidIPv6CIDR) {
            return true;
        }

        // Input is not a valid IP address, wildcard IP address, or CIDR address string
        return false;
    }

    //Do dynamic checking to see if the IP looks like a real ip
    $("#ipAddressInput").on("input", function() {
        $(this).val($(this).val().trim());
            var ipAddress = $(this).val();
        if (!isValidIpFilter(ipAddress)) {
            $(this).parent().addClass("error");
        } else {
            $(this).parent().removeClass("error");
        }
    });

    $("#ipAddressInputWhitelist").on("input", function() {
        $(this).val($(this).val().trim());
            var ipAddress = $(this).val();
        if (!isValidIpFilter(ipAddress)) {
            $(this).parent().addClass("error");
        } else {
            $(this).parent().removeClass("error");
        }
    });

    function isLAN(ipAddress) {
        function ip2long(ipAddress) {
            // Convert the IP address to a 32-bit integer
            const parts = ipAddress.split(".");
            return (
                (parseInt(parts[0]) << 24) |
                (parseInt(parts[1]) << 16) |
                (parseInt(parts[2]) << 8) |
                parseInt(parts[3])
            );
        }

        // Define the LAN IP address ranges
        const LAN_RANGES = [
            { start: "10.0.0.0", end: "10.255.255.255" },
            { start: "172.16.0.0", end: "172.31.255.255" },
            { start: "192.168.0.0", end: "192.168.255.255" }
        ];

        // Check if the IP address is within any of the LAN ranges
        for (let i = 0; i < LAN_RANGES.length; i++) {
            const rangeStart = ip2long(LAN_RANGES[i].start);
            const rangeEnd = ip2long(LAN_RANGES[i].end);
            const ipAddressLong = ip2long(ipAddress);

            if (ipAddressLong >= rangeStart && ipAddressLong <= rangeEnd) {
            return true;
            }
        }

        return false;
    }

    function isHomeAddr(ipAddress) {
        const specialIpAddresses = ['0.0.0.0', '127.0.0.1', '::1'];
        return specialIpAddresses.includes(ipAddress);
    }


    
    //Load the summary to ip access table
    function initBlacklistQuickBanTable(){
        $.get("/api/quickban/list", function(data){
            //Convert the data to a dictionary
            var ipAccessCounts = {};
            access_ip_country_map = {};
            data.forEach(function(entry){
               ipAccessCounts[entry.IpAddr] = entry.Count
               access_ip_country_map[entry.IpAddr] = entry.CountryCode;
            });
            initIpAccessTable(ipAccessCounts);
        })
    }
    initBlacklistQuickBanTable();

    function getCountryISOFromQuickBan(ip){
        if (access_ip_country_map[ip] === "") {
            return "LAN / Reserved";
        }
        return access_ip_country_map[ip];
    }

    var blacklist_entriesPerPage = 30;
    var blacklist_currentPage = 1;
    var blacklist_totalPages = 0;
    var access_ip_country_map = {};

    function initIpAccessTable(ipAccessCounts){
        // Filter out IPs with less than 100 requests
        var filteredCounts = {};
        for (var ip in ipAccessCounts) {
            if (ipAccessCounts[ip] >= 100) {
                filteredCounts[ip] = ipAccessCounts[ip];
            }
        }
        ipAccessCounts = filteredCounts;
        blacklist_currentPage = 1; // Reset to first page
        blacklist_totalPages = Math.ceil(Object.keys(ipAccessCounts).length / blacklist_entriesPerPage);

        function sortkv(obj) {
            var sortable = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                sortable.push([key, obj[key]]);
                }
            }
            sortable.sort(function(a, b) {
                return b[1] - a[1];
            });
            var sortedObj = {};
            sortable.forEach(function(item) {
                sortedObj[item[0]] = item[1];
            });
            return sortedObj;
        }

        ipAccessCounts = sortkv(ipAccessCounts);

        function renderTable() {
            var tableBody = $("#ipTable tbody");
            tableBody.empty();

            var startIndex = (blacklist_currentPage - 1) * blacklist_entriesPerPage;
            var endIndex = startIndex + blacklist_entriesPerPage;
            var slicedEntries = Object.entries(ipAccessCounts).slice(startIndex, endIndex);

            slicedEntries.forEach(function([ip, accessCount]) {
                var row = $("<tr>").appendTo(tableBody);
                $("<td>").text(ip).appendTo(row);
                $("<td>").text(accessCount).appendTo(row);
                $("<td>").text(getCountryISOFromQuickBan(ip)).appendTo(row);
                if (ipInBlacklist(ip)){
                    $("<td>").html(`<button class="ui basic green tiny icon button" title"Unban IP" onclick="handleUnban('${ip}');"><i class="green check icon"></i></button>`).appendTo(row);
                }else{
                    $("<td>").html(`<button class="ui basic red tiny icon button" title"Ban IP" onclick="handleBanIp('${ip}');"><i class="red ban icon"></i></button>`).appendTo(row);
                }
            });

            if (slicedEntries.length == 0){
                var row = $("<tr>").appendTo(tableBody);
                $("<td colspan='4'>").html(`
                    <i class="ui green circle check icon"></i> There are no HTTP requests recorded today     
                `).appendTo(row);
                
            }
        }

        function renderPagination() {
            var paginationDiv = $(".pagination");
            paginationDiv.empty();

            for (var i = 1; i <= blacklist_totalPages; i++) {
                var button = $("<button>").text(i).addClass("ui small basic compact button");
                if (i === blacklist_currentPage) {
                    button.addClass("disabled");
                }
                button.click(function() {
                    blacklist_currentPage = parseInt($(this).text());
                    renderTable();
                    renderPagination();
                });
                button.appendTo(paginationDiv);
            }
        }

        renderTable();
        renderPagination();
    }

    function ipInBlacklist(targetIp){
        let inBlacklist = false;
        $(".blacklistItem").each(function(){
            if ($(this).attr("ip") == encodeURIComponent(targetIp)){
                inBlacklist = true;
            }   
        });
        return inBlacklist;
    }

    function handleBanIp(targetIp){
        $("#ipAddressInput").val(targetIp);
        addIpBlacklist();
    }

    function handleUnban(targetIp){
        removeIpBlacklist(targetIp);
    }

    //Bind UI events
    $(".advanceSettings").accordion();
</script>